package com.ebupt.migu.music.api.controller;

import com.ebupt.migu.music.api.service.DataService;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.CSVUtils;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.propagate.pojo.vo.UploadVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/data")
public class DataController {
    @Value("${happiness.upload}")
    private String HAPPINESS_UPLOAD_PATH;
    @Value("${happiness.backup}")
    private String HAPPINESS_BACKUP_PATH;

    @Autowired
    private DataService dataService;

    @RequestMapping(value = "/success", method = RequestMethod.POST)
    public String success(@RequestParam(value = "sid", required = false) String sid,
        @RequestParam(value = "date", required = false) String date) {
        log.info("策略ID：{}， 策略执行时间：{}", sid, date);
        return dataService.success(sid, date);
    }

    @RequestMapping(value = "/happiness/upload")
    public ResultObject happiness(MultipartFile file) {
        ResultObject res = new ResultObject();
        try {
            boolean isCsv = CSVUtils.validateUploadFile(file, "csv");
            if (!isCsv) {
                throw new MyException(StatusEnum.UPLOAD, "文件格式或内容异常！");
            }
            Date date = new Date();
            String upload = HAPPINESS_UPLOAD_PATH + "happiness.csv";
            String backup = HAPPINESS_BACKUP_PATH
                + DateUtil.parseDateToStr(date, DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS) + ".csv";
            CSVUtils.upload(file, upload);
            CSVUtils.upload(file, backup);
            return res.success("上传成功");
        } catch (Exception e) {
            res.setCode(StatusEnum.ERROR.getCode());
            res.setMsg(StatusEnum.ERROR.getMsg());
            return res;
        }
    }
}
